package com.gzc.just.play.last.war.sceneserver.battle.heartbeat;

import com.gzc.just.play.last.war.sceneserver.battle.service.BattleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 战斗心跳管理器
 * 定期处理战斗相关的心跳事件
 * 对应C++的OnBattleHeartBeat
 */
@Component
public class BattleHeartbeatManager {
    
    private static final Logger log = LoggerFactory.getLogger(BattleHeartbeatManager.class);
    
    @Autowired
    private BattleService battleService;
    
    /** 心跳时间间隔（毫秒） */
    private static final long HEARTBEAT_INTERVAL = 1000; // 1秒
    
    /** 最后一次心跳时间 */
    private long lastHeartbeatTime = System.currentTimeMillis();
    
    /** 心跳计数 */
    private long heartbeatCount = 0;
    
    /**
     * 处理战斗心跳
     * 每1秒执行一次
     */
    @Scheduled(fixedRate = HEARTBEAT_INTERVAL)
    public void processHeartbeat() {
        long currentTime = System.currentTimeMillis();
        long tickSpan = currentTime - lastHeartbeatTime;
        lastHeartbeatTime = currentTime;
        
        heartbeatCount++;
        
        try {
            // 处理战斗心跳
            battleService.processBattleHeartbeat();
            
            // 每10秒输出一次日志
            if (heartbeatCount % 10 == 0) {
                logHeartbeatStatus();
            }
        } catch (Exception e) {
            log.error("Error processing battle heartbeat", e);
        }
    }
    
    /**
     * 输出心跳状态日志
     */
    private void logHeartbeatStatus() {
        int activeBattleCount = battleService.getActiveBattleCount();
        
        log.debug("Battle heartbeat status - heartbeat count: {}, active battle count: {}, time: {}", 
                heartbeatCount, activeBattleCount, new Date());
    }
    
    /**
     * 获取最后一次心跳时间
     */
    public long getLastHeartbeatTime() {
        return lastHeartbeatTime;
    }
    
    /**
     * 获取心跳计数
     */
    public long getHeartbeatCount() {
        return heartbeatCount;
    }
    
    /**
     * 重置心跳计数
     */
    public void resetHeartbeatCount() {
        heartbeatCount = 0;
    }
}
